package com.anda.logistics.map.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.anda.logistics.util.QueryFilter;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CommUtil {
	public static String getDate8FromDate(Date date){
		if ( date == null ) return null;
		return new SimpleDateFormat("yyyy-MM-dd").format(date);
	}
	public static String getDate17FromDate(Date date){
		if ( date == null ) return null;
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}
	
	public static String encode(String s){
		if ( null == s) return null;
		String r = null;
		try {
			r = URLEncoder.encode (URLEncoder.encode(s, "utf-8"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return r;
	}
	public static String getJsonString(Object o){
		ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
		try {
			return encode( mapper.writeValueAsString(o));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return "";
	}
	public static <T> T jsonToObject(String json, Class<T> clazz){
		ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
		try {
			return mapper.readValue ( decodeUrlStr(json, true), clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Long[] getLongs(long[] ls){
		Long[] r = new Long[ls.length];
		for(int i= ls.length -1; i>= 0; i-=1){
			r[i] = ls[i];
		}
		return r;
	}
	public static Integer[] getIntsFromLongs(long[] ls){
		Integer[] r = new Integer[ls.length];
		for(int i= ls.length -1; i>= 0; i-=1){
			r[i] = (int)ls[i];
		}
		return r;
	}
	
	public static String decodeUrlStr(String s, boolean decode){
		if (s.equals("null")) return null;
		try {
			if (decode) return URLDecoder.decode(s, "utf-8");
			return s;
		} catch (Exception e){
			return null;
		}
	}
	
	public static void main(String [] args){
		QueryFilter filter = new QueryFilter(new long[]{2L,3L,4L,6L});
		Map m = new HashMap();
		m.put("k","v");
		m.put("k1","v1");
		filter.setMap(m);
		String json = getJsonString(filter);
		System.out.println(json);
		QueryFilter f = jsonToObject( decodeUrlStr(json,true), QueryFilter.class);
		System.out.println(f);
		
	}
}
